<template>
    <div class="app-container">
      <!-- 搜索区域 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true">
       <div style="float: left;">
        <el-form-item label="产线选择" prop="line_id">
          <el-select v-model="queryParams.line" multiple clearable collapse-tags placeholder="请选择产线"
            popper-class="custom-header" :max-collapse-tags="1" style="width: 200px" @change="updateCheckAllStatus">
            <el-checkbox style="margin-left: 10px;margin-bottom: 5px;" v-model="checkAll" :indeterminate="indeterminate"
              @change="handleCheckAll">
              All
            </el-checkbox>
            <el-option v-for="item in lineList" :key="item.line_id" :label="item.line_name" :value="item.line_id" />
          </el-select>
  
        </el-form-item>
  
        <el-form-item label="MPN" prop="MPN_name">
          <el-input v-model="queryParams.MPN_name" placeholder="请输入品目名称" clearable />
        </el-form-item>
  
        <el-form-item label="测定日期" prop="query_time">
          <el-date-picker v-model="queryParams.query_time" type="daterange" range-separator="至" start-placeholder="开始时间"
            end-placeholder="结束时间" value-format="yyyy-MM-dd" />
        </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getCTList">搜索</el-button>
            <el-button type="primary" @click="resetButton">重置</el-button>
          </el-form-item>
       </div>
  
  
       
      </el-form>
  
      <!-- 数据表格 -->
      <el-table :data="tableData" border style="width: 100%" height="600px" @row-dblclick="handleRowDblClick">
        <el-table-column v-if="false" label="编号" prop="mpn_id" align="center" />
        <el-table-column label="序号" prop="serial_number" align="center" />
        <el-table-column v-if="false" label="ID" prop="ct_id" align="center" />
        <el-table-column label="品目名称" prop="mpn_name" align="center" />
        <el-table-column label="内部名称" prop="internal_name" align="center" />
        <el-table-column label="工程名称" prop="project_name" align="center" />
        <el-table-column label="工艺名称" prop="process_name" align="center" />
        <el-table-column label="基准CT" prop="benchmark_value" align="center" />
        <el-table-column label="测定日期" prop="enter_data" align="center" />
        <el-table-column v-for="(col, index) in dynamicColumns" :key="index" :label="`参数${index + 1}`" align="center"
          width="80">
          <template slot-scope="scope">
            <span :class="getColorClass(scope.row.benchmark_value, getValue(scope.row.test_values, index))">
              {{ getValue(scope.row.test_values, index) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="平均" align="center" width="80">
          <template slot-scope="scope">
            <span :class="getColorClass(scope.row.benchmark_value, getAVGValue(scope.row.test_values))">
              {{ getAVGValue(scope.row.test_values) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="异常原因" prop="exception_cause" align="center" />
        <el-table-column label="对策措施" prop="countermeasure" align="center" />
        <el-table-column label="纳期" prop="acceptance" align="center" />
        <el-table-column label="负责人" prop="npi" align="center" />
        <el-table-column label="Process" prop="process" align="center" />
        <el-table-column label="IE" prop="ie" align="center" />
        <el-table-column label="负荷表组合名称" prop="ic_name" align="center" />
        <el-table-column label="DFF" prop="dff" align="center" />
        <el-table-column label="psc/sheet" prop="psc_sheet" align="center" />
        <el-table-column label="设备配置" prop="device_config" align="center" />
        <el-table-column label="Line NO" prop="line_name" align="center" />
        <el-table-column label="部门" prop="dept_name" align="center" />
        <el-table-column label="课别" prop="class_name" align="center" />
        <el-table-column label="楼层" prop="floor" align="center" />
        <el-table-column label="BU" prop="bu" align="center" />
        <el-table-column label="DFF" align="center">
          <template slot-scope="scope">
            {{ scope.row.internal_name + "" + scope.row.process }}
          </template>
        </el-table-column>
        <el-table-column label="对碰名称" align="center">
          <template slot-scope="scope">
            {{ scope.row.internal_name + "" + scope.row.ie }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getCTList" />
  
  
      <!-- 新增/修改界面 -->
      <el-dialog :title="title" :visible.sync="dialogVisibleCTform" width="30%" :before-close="cancel">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="品目id" prop="MPN_Id" v-show="false">
            <el-input v-model="form.mpn_id" />
          </el-form-item>
          <el-form-item label="品目名称" prop="mpn_name">
            <el-input v-model="form.mpn_name" placeholder="请输入品目名称" />
          </el-form-item>
          <el-form-item label="内部名称" prop="internal_name">
            <el-input v-model="form.internal_name" placeholder="请输入内部名称" />
          </el-form-item>
          <el-form-item label="工程名称" prop="project_name">
            <el-input v-model="form.project_name" placeholder="请输入工程名称" />
          </el-form-item>
          <el-form-item label="工艺名称" prop="process_name">
            <el-input v-model="form.process_name" placeholder="请输入工艺名称" />
          </el-form-item>
          <el-form-item label="产线" prop="line_name">
            <el-input v-model="form.line_name" disabled />
          </el-form-item>
          <el-form-item label="基准CT" prop="benchmark_value">
            <el-input v-model="form.benchmark_value" placeholder="请输入基准CT" />
          </el-form-item>
          <el-form-item label="参数1" prop="test_values1">
            <el-input v-model="form.test_values[0]" placeholder="参数1" />
          </el-form-item>
          <el-form-item label="参数2" prop="test_values2">
            <el-input v-model="form.test_values[1]" placeholder="参数2" />
          </el-form-item>
          <el-form-item label="参数3" prop="test_values1">
            <el-input v-model="form.test_values[2]" placeholder="参数3" />
          </el-form-item>
          <el-form-item label="参数4" prop="test_values1">
            <el-input v-model="form.test_values[3]" placeholder="参数4" />
          </el-form-item>
          <el-form-item label="参数5" prop="test_values1">
            <el-input v-model="form.test_values[4]" placeholder="参数5" />
          </el-form-item>
          <el-form-item label="参数6" prop="test_values1">
            <el-input v-model="form.test_values[5]" placeholder="参数6" />
          </el-form-item>
          <el-form-item label="参数7" prop="test_values1">
            <el-input v-model="form.test_values[6]" placeholder="参数7" />
          </el-form-item>
          <el-form-item label="参数8" prop="test_values1">
            <el-input v-model="form.test_values[7]" placeholder="参数8" />
          </el-form-item>
          <el-form-item label="参数9" prop="test_values1">
            <el-input v-model="form.test_values[8]" placeholder="参数9" />
          </el-form-item>
          <el-form-item label="参数10" prop="test_values1">
            <el-input v-model="form.test_values[9]" placeholder="参数10" />
          </el-form-item>
          <el-form-item label="测定日期" prop="enter_data">
            <el-date-picker v-model="form.enter_data" type="date" value-format="yyyy-MM-dd" />
          </el-form-item>
          <el-form-item label="异常原因" prop="exception_cause">
            <el-input v-model="form.exception_cause" placeholder="请输入异常原因" />
          </el-form-item>
          <el-form-item label="对策措施" prop="countermeasure">
            <el-input v-model="form.countermeasure" placeholder="请输入对策措施" />
          </el-form-item>
          <el-form-item label="纳期" prop="acceptance">
            <el-date-picker v-model="form.acceptance" type="date" value-format="yyyy-MM-dd" />
          </el-form-item>
          <el-form-item label="负责人" prop="npi">
            <el-input v-model="form.npi" placeholder="请输入NPI" />
          </el-form-item>
          <el-form-item label="Process" prop="process">
            <el-input v-model="form.process" placeholder="请输入process" />
          </el-form-item>
          <el-form-item label="IE" prop="ie">
            <el-input v-model="form.ie" placeholder="请输入ie" />
          </el-form-item>
          <el-form-item label="负荷表组合名称" prop="ic_name">
            <el-input v-model="form.ic_name" placeholder="请输入负荷表组合名称" />
          </el-form-item>
          <el-form-item label="制品长度" prop="DFF">
            <el-input v-model="form.dff" placeholder="请输入制品长度" />
          </el-form-item>
          <el-form-item label="psc/sheet" prop="psc_sheet">
            <el-input v-model="form.psc_sheet" placeholder="请输入psc/sheet" />
          </el-form-item>
          <el-form-item label="设备配置" prop="device_config">
            <el-input v-model="form.device_config" placeholder="请输入设备配置" />
          </el-form-item>
          <el-form-item label="部门" prop="dept_name">
            <el-input v-model="form.dept_name" placeholder="请输入部门" />
          </el-form-item>
          <el-form-item label="课别" prop="class_name">
            <el-input v-model="form.class_name" placeholder="请输入课别" />
          </el-form-item>
          <el-form-item label="楼层" prop="floor">
            <el-input v-model="form.floor" placeholder="请输入楼层" />
          </el-form-item>
          <el-form-item label="BU" prop="bu">
            <el-input v-model="form.bu" placeholder="请输入BU" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
  
  
    </div>
  </template>
  
  <script>
  import { getUserLinkLineByLogin, getCTTableByLineIdEnterDateMPNName, setCTtable, ctExport,importctExcel ,exportctTemplate,delct} from "@/api/ctManage/MPNManage"
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import Treeselect from "@riophae/vue-treeselect";
  import "splitpanes/dist/splitpanes.css";
  
  export default {
    name: "sampleDel",
    components: { Treeselect },
    data() {
      return {
        form: {
          test_values: []
        },
        dialogVisibleCTform: false,
        // 新增全选状态变量
        checkAll: false,         // 全选状态
        indeterminate: false,    // 半选状态
        //产线参数
        lineList: [],
        //测试参数初始化列表
        dynamicColumns: Array(10).fill({}),
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          MPN_name: '',
          query_time: [],
          line: []   // 确保初始化为数组
        },
        // 表格数据
        tableData: [],
        // 总条数
        total: 0,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        dialogVisible: false,
        // 表单验证规则
        rules: {
          internal_name: [
            { required: true, message: "内部名称不能为空", trigger: "blur" },
          ],
          project_name: [
            { required: true, message: "工程名称不能为空", trigger: "blur" },
          ],
          process_name: [
            { required: true, message: "工艺名称不能为空", trigger: "blur" },
          ],
          mpn_name: [
            { required: true, message: "品目名不能为空", trigger: "blur" },
          ],
          line: [
            { required: true, message: "请选择产线", trigger: "blur" },
          ],
          benchmark_value: [
            { required: true, message: "基准CT不能为空", trigger: "blur" },
            { pattern: /^\d*\.?\d*$/, message: '只能输入数字和小数点', trigger: 'blur' }
          ],
          process: [
            { required: true, message: "process不能为空", trigger: "blur" },
          ],
          ie: [
            { required: true, message: "IE不能为空", trigger: "blur" },
          ],
          ic_name: [
            { required: true, message: "组合名称不能为空", trigger: "blur" },
          ],
          psc_sheet: [
            { pattern: /^\d*\.?\d*$/, message: '只能输入数字和小数点', trigger: 'blur' }
          ]
        },
      };
    },
    created() {
      this.getUserLine()
    },
    methods: {
      
      //关闭按钮
      cancel() {
        this.dialogVisibleCTform = false;
        this.getCTList();
      },
      // 双击行处理方法
      handleRowDblClick(row, column, event) {
        this.handleAdd(row, '修改');
      },
      // 新增按钮
      handleAdd(data, title) {
        this.dialogVisibleCTform = true;
        // 清空表单
        this.form = data;
        if (data.enter_data == '') {
          this.form.enter_data = new Date().toISOString().split('T')[0];
        }
        this.title = title;
      },
      //获取平均值
      getAVGValue(values) {
        var addvalues = 0.0;
        for (let index = 0; index < values.length; index++) {
          addvalues += values[index]
        }
        return Number(addvalues / values.length).toFixed(2);
  
      },
      //获取当前登录用户链接的全部产线
      getUserLine() {
        getUserLinkLineByLogin().then(response => {
          this.lineList = response;
          // 初始化全选状态
          this.updateCheckAllStatus();
        })
      },
      //获取测试用的值
      getValue(values, index) {
        if (!values || index >= values.length) return '--';
        // 保留两位小数
        return Number(values[index]).toFixed(2);
      },
      //查询样本
      getCTList() {
        getCTTableByLineIdEnterDateMPNName(this.queryParams.pageNum, this.queryParams.pageSize, this.queryParams.MPN_name, this.queryParams.line, this.queryParams.query_time[0], this.queryParams.query_time[1]).then(response => {
          this.tableData = [];
          this.total = response.total;
          for (let index = 0; index < response.list.length; index++) {
            const element = response.list[index];
            this.tableData.push({
              serial_number: index + 1,
              ct_id: element.ct_id,
              mpn_name: element.mpn_name,
              internal_name: element.internal_name,
              project_name: element.project_name,
              process_name: element.process_name,
              line_name: element.line.line_name,
              mpn_id: element.mpn_id,
              benchmark_value: element.benchmark_value,
              enter_data: element.enter_data,
              test_values: this.testValues(element.test_values),
              exception_cause: element.exception_cause,
              countermeasure: element.countermeasure,
              acceptance: element.acceptance,
              process: element.process,
              ic_name: element.ic_name,
              psc_sheet: element.psc_sheet,
              device_config: element.device_config,
              state: element.state,
              dept_name: element.dept_name,
              class_name: element.class_name,
              floor: element.floor,
              npi: element.npi,
              dff: element.dff,
              ie: element.ie,
              bu: element.bu
            })
          }
  
        })
  
  
      },
      //测试数值初始化
      testValues(value) {
        if (value != "") {
          return JSON.parse(value);
        } else {
          return []
        }
      },
      //重置
      resetButton() {
        this.queryParams.MPN_name = '',
          this.queryParams.query_time = [],
          this.queryParams.line = []
      },
      // 编辑按钮
      handleEdit(row) {
        this.resetForm();
        this.form = Object.assign({}, row);
        this.open = true;
        this.title = "修改样本";
      },
      // 删除按钮
      handleDelete(row) {
        this.$confirm('确认删除该样本？', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            delct(row.ct_id).then(response => {
              if (response > 0) {
                this.$message.success("删除成功");
                this.getCTList();
              } else {
                this.$message.success("删除失败");
              }
            })
          })
          .catch(() => { });
      },
      // 表单提交
      submitForm() {
        this.$refs["form"].validate((valid) => {
          var state;
          if(this.form.ct_id>0){
            state='修改'
          }else{
            state='添加'
          }
          if (valid) {
            setCTtable(this.form).then(response => {
              if (response > 0) {
                this.$message.success(state+"成功");
                this.getCTList();
              } else {
                this.$message.error(state+"失败");
              }
            })
            this.dialogVisibleCTform = false;
          }
        });
      },
      // 新增：全选处理函数
      handleCheckAll(val) {
        // val: 全选复选框的当前状态 (true/false)
        if (val) {
          // 全选：将所有产线ID加入数组
          this.queryParams.line = this.lineList.map(item => item.line_id);
        } else {
          // 取消全选：清空数组
          this.queryParams.line = [];
        }
        // 取消半选状态
        this.indeterminate = false;
      },
  
      // 新增：更新全选状态
      updateCheckAllStatus() {
        const selectedCount = this.queryParams.line.length;
        const totalCount = this.lineList.length;
  
        // 更新全选状态
        this.checkAll = selectedCount === totalCount && totalCount > 0;
        // 更新半选状态（部分选择时）
        this.indeterminate = selectedCount > 0 && selectedCount < totalCount;
      },
      //导入
      handleImport(file) {
        const formData = new FormData();
        formData.append("file",file.raw);
        importctExcel(formData).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.getCTList();
        }).catch(error => {
          this.$modal.msgError(error);
        });
      },
  
      //导入模板
      downloadTemplate() {
        exportctTemplate().then(res => {
          // 处理blob下载
          const blob = new Blob([res], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          });
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.download = '数据导入模板.xlsx';
          link.click();
        });
  
      }
    },
  
    mounted() {
    }
  };
  </script>
  
  <style scoped>
  .ml10 {
    margin-left: 10px;
  }
  
  .normal-color {
    color: #67C23A;
    /* 绿色 - 正常 */
  }
  
  .warning-color {
    color: #E6A23C;
    /* 黄色 - 警告 */
  }
  
  .danger-color {
    color: #F56C6C;
    /* 红色 - 危险 */
  }
  
  /* 状态样式 */
  .status-normal {
    color: #67C23A;
    background: #f0f9eb;
    padding: 5px 10px;
    border-radius: 4px;
    display: inline-block;
  }
  
  .status-warning {
    color: #E6A23C;
    background: #fdf6ec;
    padding: 5px 10px;
    border-radius: 4px;
    display: inline-block;
  }
  
  .status-expired {
    color: #F56C6C;
    background: #fef0f0;
    padding: 5px 10px;
    border-radius: 4px;
    display: inline-block;
  }
  </style>
  